package com.lxw.nonghe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxw.nonghe.annotation.RequiresPermission;
import com.lxw.nonghe.common.Result;
import com.lxw.nonghe.entity.AnnualFeeStandard;
import com.lxw.nonghe.entity.FamilyPayment;
import com.lxw.nonghe.entity.Farmer;
import com.lxw.nonghe.service.AnnualFeeStandardService;
import com.lxw.nonghe.service.FamilyPaymentService;
import com.lxw.nonghe.service.FarmerService;
import com.lxw.nonghe.util.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 家庭缴费记录表 前端控制器
 * </p>
 *
 * @author lxw
 * @since 2025-05-15
 */
@RestController
@RequestMapping("/familyPayment")
@RequiresPermission("payment:manage")
public class FamilyPaymentController {

    @Autowired
    private FamilyPaymentService paymentService;
    @Autowired
    private FarmerService farmerService;
    @Autowired
    private AnnualFeeStandardService annualFeeStandardService;

    @Autowired
    private LogUtils logUtils;


    @GetMapping("/getCurrentYearFeeAmount")
    public Result<BigDecimal> getCurrentYearFeeAmount() {
        try {
            // 获取当前年份（2025年，可动态获取）
            int currentYear = LocalDate.now().getYear(); // 动态获取当前年份，避免硬编码
            // 查询当前年份且状态为启用（status=1）的缴费标准
            AnnualFeeStandard queryParam = new AnnualFeeStandard();
            queryParam.setYear(currentYear);
            queryParam.setStatus((byte) 1); // 1表示启用状态

            // 调用服务层获取单个结果
            AnnualFeeStandard feeStandard = annualFeeStandardService.list(
                    new LambdaQueryWrapper<AnnualFeeStandard>()
                            .eq(AnnualFeeStandard::getYear, currentYear)
                            .eq(AnnualFeeStandard::getStatus, 1)
            ).stream().findFirst().orElse(null);

            if (feeStandard != null) {
                BigDecimal amount = feeStandard.getAmount();
                //logUtils.recordLog("家庭缴费管理", "查询当前年度缴费金额", "成功", "年份:" + currentYear + ", 金额:" + amount);
                return Result.success("当前年度缴费金额查询成功", amount);
            } else {
                logUtils.recordLog("家庭缴费管理", "查询当前年度缴费金额", "失败", "年份:" + currentYear + " 无有效的缴费标准");
                return Result.error("未找到当前年度的有效缴费标准");
            }

        } catch (Exception e) {
            logUtils.recordLog("家庭缴费管理", "查询当前年度缴费金额", "失败", e.getMessage());
            return Result.error("查询异常: " + e.getMessage());
        }
    }
    /**
     * 根据家庭ID查询对应的农民姓名列表
     * @param familyId 家庭ID
     * @return 包含农民姓名列表的结果对象
     */
    @GetMapping("/getNamesByFamilyId/{familyId}")
    public Result<List<String>> getNamesByFamilyId(@PathVariable Integer familyId) {
        try {
            // 根据familyId查询对应的农民信息
            List<Farmer> farmers = farmerService.getFarmersByFamilyId(familyId);

            // 如果找到了农民信息，提取所有姓名
            if (farmers != null &&!farmers.isEmpty()) {
                List<String> names = farmers.stream()
                        .map(Farmer::getName)
                        .collect(Collectors.toList());
                return Result.success("查询成功", names);
            } else {
                logUtils.recordLog("家庭缴费管理", "根据家庭ID查询姓名列表", "失败", "家庭ID:" + familyId + "不存在对应的农民记录");
                return Result.error("未找到对应的农民记录");
            }
        } catch (Exception e) {
            logUtils.recordLog("家庭缴费管理", "根据家庭ID查询姓名列表", "失败", e.getMessage());
            return Result.error("查询异常: " + e.getMessage());
        }
    }
    @PostMapping("/updateCooperativeStatus")
    public Result<Boolean> updateCooperativeStatus(@RequestBody Map<String, Object> params) {
        Integer familyId = (Integer) params.get("familyId");
        List<String> names = (List<String>) params.get("names");
        try {
            if (familyId == null || CollectionUtils.isEmpty(names)) {
                logUtils.recordLog("家庭缴费管理", "批量修改参合状态", "失败", "家庭ID或姓名列表为空");
                return Result.error("家庭ID和姓名列表均为必填参数");
            }

            // 1. 根据familyId和names查询符合条件的农民列表
            LambdaQueryWrapper<Farmer> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Farmer::getFamilyId, familyId)
                    .in(Farmer::getName, names); // 姓名精确匹配（可根据需求改为模糊匹配like）
            List<Farmer> farmersToUpdate = farmerService.list(wrapper);

            if (farmersToUpdate.isEmpty()) {
                logUtils.recordLog("家庭缴费管理", "批量修改参合状态", "失败",
                        "家庭ID:" + familyId + ", 姓名列表:" + names + " 未找到对应农民记录");
                return Result.error("未找到符合条件的农民记录");
            }

            // 2. 批量更新isCooperative为1（使用MyBatis-Plus的updateBatchById）
            List<Farmer> updatedFarmers = farmersToUpdate.stream()
                    .peek(farmer -> farmer.setIsCooperative(1)) // 设置状态为1
                    .collect(Collectors.toList());

            boolean updateResult = farmerService.updateBatchById(updatedFarmers);

            if (updateResult) {
                logUtils.recordLog("家庭缴费管理", "批量修改参合状态", "成功",
                        "家庭ID:" + familyId + ", 姓名列表:" + names + " 修改成功");
                return Result.success("参合状态修改成功", true);
            } else {
                logUtils.recordLog("家庭缴费管理", "批量修改参合状态", "失败",
                        "家庭ID:" + familyId + ", 姓名列表:" + names + " 数据库更新失败");
                return Result.error("参合状态修改失败");
            }

        } catch (Exception e) {
            logUtils.recordLog("家庭缴费管理", "批量修改参合状态", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/create")
    public Result<Boolean> addPayment(@RequestBody FamilyPayment payment) {
        try {
            // 初始化创建时间
            payment.setCreateTime(new Date());

            boolean result = paymentService.save(payment);
            if (result) {
                logUtils.recordLog("家庭缴费管理", "新增缴费记录", "成功",
                        "家庭ID:" + payment.getFamilyId() + ", 金额:" + payment.getTotalAmount());
                return Result.success("家庭缴费记录新增成功", true);
            } else {
                logUtils.recordLog("家庭缴费管理", "新增缴费记录", "失败", "保存数据库失败");
                return Result.error("家庭缴费记录新增失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("家庭缴费管理", "新增缴费记录", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/delete/{id}")
    public Result<Boolean> deletePayment(@PathVariable Integer id) {
        try {
            FamilyPayment payment = paymentService.getById(id);
            boolean result = paymentService.removeById(id);

            if (result) {
                logUtils.recordLog("家庭缴费管理", "删除缴费记录", "成功",
                        "记录ID:" + id + ", 家庭ID:" + (payment != null ? payment.getFamilyId() : "未知"));
                return Result.success("家庭缴费记录删除成功", true);
            } else {
                logUtils.recordLog("家庭缴费管理", "删除缴费记录", "失败", "记录ID:" + id + "不存在");
                return Result.error("家庭缴费记录删除失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("家庭缴费管理", "删除缴费记录", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    public Result<Boolean> updatePayment(@RequestBody FamilyPayment payment) {
        try {
            boolean result = paymentService.updateById(payment);
            if (result) {
                logUtils.recordLog("家庭缴费管理", "更新缴费记录", "成功",
                        "记录ID:" + payment.getPaymentId());
                return Result.success("家庭缴费记录更新成功", true);
            } else {
                logUtils.recordLog("家庭缴费管理", "更新缴费记录", "失败",
                        "记录ID:" + payment.getPaymentId() + "不存在");
                return Result.error("家庭缴费记录更新失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("家庭缴费管理", "更新缴费记录", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @GetMapping("/get/{id}")
    public Result<FamilyPayment> getPaymentById(@PathVariable Integer id) {
        try {
            FamilyPayment payment = paymentService.getById(id);
            if (payment != null) {
                return Result.success("家庭缴费记录查询成功", payment);
            } else {
                logUtils.recordLog("家庭缴费管理", "查询缴费详情", "失败", "记录ID:" + id + "不存在");
                return Result.error("未找到该家庭缴费记录");
            }
        } catch (Exception e) {
            logUtils.recordLog("家庭缴费管理", "查询缴费详情", "失败", e.getMessage());
            return Result.error("查询异常: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    public Result<Page<FamilyPayment>> getPaymentPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Integer familyId,
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false) String payerName) {
        try {
            Page<FamilyPayment> page = paymentService.getPaymentPage(
                    current, size, familyId, year, payerName);
            return Result.success("家庭缴费记录分页查询成功", page);
        } catch (Exception e) {
            logUtils.recordLog("家庭缴费管理", "分页查询缴费", "失败", e.getMessage());
            return Result.error("分页查询异常: " + e.getMessage());
        }
    }

    @PostMapping("/query")
    public Result<Page<FamilyPayment>> queryPayments(
            @RequestBody FamilyPayment queryParam,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<FamilyPayment> page = paymentService.queryPayments(queryParam, current, size);
            return Result.success("家庭缴费记录条件查询成功", page);
        } catch (Exception e) {
            logUtils.recordLog("家庭缴费管理", "条件查询缴费", "失败", e.getMessage());
            return Result.error("条件查询异常: " + e.getMessage());
        }
    }

    @GetMapping("/statistics/yearly")
    public Result<Map<Integer, BigDecimal>> getYearlyPaymentStatistics() {
        try {
            Map<Integer, BigDecimal> statistics = paymentService.getYearlyPaymentStatistics();
            return Result.success("年度缴费统计查询成功", statistics);
        } catch (Exception e) {
            logUtils.recordLog("家庭缴费管理", "年度缴费统计", "失败", e.getMessage());
            return Result.error("统计查询异常: " + e.getMessage());
        }
    }
    /**
     * 根据家庭ID和姓名获取身份证号
     * @param familyId 家庭ID
     * @param name 姓名
     * @return 身份证号
     */
    @GetMapping("/getIdCardByFamilyIdAndName")
    public Result<String> getIdCardByFamilyIdAndName(
            @RequestParam Integer familyId,
            @RequestParam String name) {
        try {
            String idCard = farmerService.getIdCardByFamilyIdAndName(familyId, name);
            if (idCard != null) {
                return Result.success("查询成功", idCard);
            } else {
                return Result.error("未找到对应身份证号");
            }
        } catch (Exception e) {
            return Result.error("查询异常: " + e.getMessage());
        }
    }
}
